package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FollowUserApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 小视频业务逻辑处理层
 */
@Service
@Slf4j
public class VideoService {

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Reference
    private VideoApi videoApi;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private FollowUserApi followUserApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发布小视频
     * videoThumbnail:视频封面文件
     * videoFile:视频文件
     */
    @CacheEvict(value = "videoList",allEntries = true)
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) {
        log.debug("发布小视频开始..............");
        try {
            //a.调用阿里云存储图片文件 得到图片地址
            String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
            //b.调用fastdfs存储视频文件 得到视频地址
            String filename = videoFile.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);//后缀
            StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), suffix, null);
            String videoUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
            //c.封装视频对象，调用保存视频服务方法
            Video video = new Video();
            video.setUserId(UserHolder.getUserId());//当前发布小视频用户id
            video.setPicUrl(picUrl);//图片封装地址
            video.setVideoUrl(videoUrl);//视频文件地址
            videoApi.saveVideo(video);
        } catch (IOException e) {
            throw new TanHuaException(ErrorResult.error());
        }
    }

    /**
     * 分页查询小视频列表
     * key= 2_10 value=PageResult<VideoVo>
     */
    @Cacheable(value = "videoList",key = "#page +'_' +#pagesize")
    public PageResult<VideoVo> queryPage(int page, int pagesize) {
        log.debug("分页查询小视频列表开始..............");
        PageResult<VideoVo> videoVoPageResult = new PageResult<>();
        //1.调用视频服务分页查询视频列表
        PageResult<Video> pageResult  = videoApi.queryPage(page,pagesize);
        if(pageResult == null || CollectionUtils.isEmpty(pageResult.getItems())){
            return new PageResult<>(0l,10l,0l,1l,null);
        } 
        //2.根据视频发布用户id  查询用户信息
        //将List<Video> UserInfo 封装成List<VideoVo>
        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video video : pageResult.getItems()) {
            VideoVo videoVo = new VideoVo();
            Long userId = video.getUserId();//发布小视频的用户id
            UserInfo userInfo = userInfoApi.queryUserInfo(userId);
            BeanUtils.copyProperties(userInfo,videoVo);//头像 昵称
            BeanUtils.copyProperties(video,videoVo);//视频文件url ，点赞数 评论数
            videoVo.setHasLiked(0);//是否点赞
            videoVo.setHasFocus(0);//是否关注
            videoVo.setSignature(video.getText());//签名
            videoVo.setCover(video.getPicUrl());//图片封面
            videoVo.setUserId(userId);//发布小视频用户id
            videoVo.setId(video.getId().toHexString());//编号
            videoVoList.add(videoVo);
        }
        //3.将视频数据 与 用户信息 封装Vo返回
        BeanUtils.copyProperties(pageResult,videoVoPageResult);
        videoVoPageResult.setItems(videoVoList);
        return videoVoPageResult;
    }

    /**
     * 视频用户关注
     */
    public void userFocus(Long friendId) {
        Long userId = UserHolder.getUserId();
        //将关注记录保存表中（调用服务FollowUser）
        FollowUser followUser = new FollowUser();
        followUser.setUserId(userId);//当前用户id
        followUser.setFollowUserId(friendId);//被关注的用户id
        followUserApi.saveFollowUser(followUser);
        //将关注记录写入redis
        String key ="followuser_"+userId+"_"+friendId;
        redisTemplate.opsForValue().set(key,"1");
    }

    /**
     * 视频用户取消关注
     */
    public void userUnFocus(Long friendId) {
        Long userId = UserHolder.getUserId();
        //将关注记录从表中删除（调用服务FollowUser）
        FollowUser followUser = new FollowUser();
        followUser.setUserId(userId);//当前用户id
        followUser.setFollowUserId(friendId);//被关注的用户id
        followUserApi.removeFollowUser(followUser);
        //将关注记录写入redis
        String key ="followuser_"+userId+"_"+friendId;
        redisTemplate.delete(key);
    }
}
